﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiniErp.Common.Cache
{
    public static class RedisMysqlCache
    {
        /// <summary>
        /// 查询缓存中数据，没有则从数据库中查询，然后更新缓存
        /// </summary>
        /// <typeparam name="T">查询的数据类型</typeparam>
        /// <param name="cache">缓存实例</param>
        /// <param name="cacheKey">缓存key</param>
        /// <param name="action">数据查询委托  范例：async () => 查询语句;</param>
        /// <param name="expire">缓存时间，不设置为一直存在  单位：毫秒</param>
        /// <returns>T类型数据</returns>
        public static async Task<T> GetDataByCacheOrDBAsync<T>(this ICache cache,
           string type, string cacheKey, Func<Task<T>> action, int expire = 0)
        {
            var data = await cache.GetAsync<T>(type, cacheKey);

            if (data == null)
            {
                data = await action();
                if (data != null)
                {
                    if (expire == 0)
                    {
                        await cache.SetAsync(type, cacheKey, data);
                    }
                    else
                    {

                        await cache.SetAsync(type, cacheKey, data, new TimeSpan(expire));
                    }

                }
            }
            return data;
        }

    }
}
